package com.tkk.monitoring.analyze.db;

import com.tkk.monitoring.analyze.AnalyzeTarget;
import com.tkk.monitoring.analyze.config.Property;
import org.apache.commons.lang.StringUtils;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.DriverManagerDataSource;

import java.io.IOException;
import java.util.List;
import java.util.Properties;

/**
 * author: Tkk
 * date: 2015/7/8
 */
public class DB {

    private static DB db;

    private DriverManagerDataSource dataSource;
    private JdbcTemplate jdbcTemplate;
    private Property property;

    public static DB getInstance() {
        if (db == null) {
            db = new DB();
        }
        return db;
    }

    public DB() {
        property = new Property("db.txt");
        dataSource = new DriverManagerDataSource();
        dataSource.setDriverClassName("com.mysql.jdbc.Driver");
        dataSource.setUrl(property.getString("url"));
        dataSource.setUsername(property.getString("u"));
        dataSource.setPassword(property.getString("p"));
        jdbcTemplate = new JdbcTemplate(dataSource);
    }

    /**
     * @param target
     * @return
     */
    public List<History> getHistory(AnalyzeTarget target) {
        return jdbcTemplate.query("SELECT * FROM history WHERE host = ? and port = ? and path = ?", new Object[]{target.getHost(), target.getPort(), target.getPath()}, new BeanPropertyRowMapper<History>(History.class));
    }

    /**
     * @param target
     * @return
     */
    public int addHistory(AnalyzeTarget target) {
        String get = null, post = null;
        if (target.getGetParam() != null) {
            get = StringUtils.join(target.getGetParam().keySet(), ",");
        }
        if (target.getPostParam() != null) {
            post = StringUtils.join(target.getPostParam().keySet(), ",");
        }
        return jdbcTemplate.update("insert into history (host,port,path,get,post) values(?,?,?,?,?)", target.getHost(), target.getPort(), target.getPath(), get, post);
    }

    /**
     * @param type
     * @param request
     * @param response
     * @param poc
     * @return
     */
    public int addPoc(String type, String request, String response, String poc) {
        return jdbcTemplate.update("insert into poc (type, request, response, poc) values(?,?,?,?)", type, request, response, poc);
    }

    /**
     * @param type
     * @return
     */
    public List<Poc> getPocByType(String type) {
        return jdbcTemplate.query("select * from poc where type = ?", new Object[]{type}, new BeanPropertyRowMapper<Poc>(Poc.class));
    }
}
